package in.smartride.server;

import in.smartride.dataInterface.RideOffer;
import in.smartride.dataInterface.DataHandler;
import in.smartride.dataInterface.userdata.UserProfile;
import in.smartride.matchingengine.FilterPreferences;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class temp
 */
public class FindRide extends HttpServlet {
	private static final long serialVersionUID = 1L;
	DataHandler dh;
	FilterPreferences fp;

	/**
	 * Default constructor.
	 */
	public FindRide() {
		dh = new DataHandler();
		fp  = new FilterPreferences();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		RideManager rm = new RideManager();
		String from = request.getParameter("from");
		String to = request.getParameter("to");
		String uId = request.getParameter("uId");
		String sdate = request.getParameter("date");
		long ldate = Long.parseLong(sdate);
		Date date = new Date(ldate);
		List<RideOffer> rideOffers = rm.processRideRequest(from, to, date, uId);

		if (rideOffers != null && rideOffers.size() != 0) {
			int i = rideOffers.size();
			while (i != 0) {
				RideOffer temp = rideOffers.get(i-1);
				if(fp.IsCompatible(temp.getUId())) {
					UserProfile up = dh.getUserProfile(temp.getUId());
					response.getWriter().write(temp.getid() + "," + temp.getFrom() + "," + temp.getTo() + "," +
						temp.getDate().toString() + "," + up.getFirstName() + "," + up.getLastName() +
						"," + up.getGender() + "," + up.getDateOfBirth().toString() + "," + 
						up.getMobileNumber() + "-");
				}
				i--;
			}
		} else {
			response.getWriter().write("-1");
		}
		System.out.println("in Find Ride");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
